package com.mmall.controller.backend;

import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.controller.basecontroller.CategoryBaseController;
import com.mmall.pojo.Product;
import com.mmall.pojo.User;
import com.mmall.service.IFileService;
import com.mmall.service.IProductService;
import com.mmall.service.IUserService;
import com.mmall.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by Administrator on 2018/11/10.
 */
@Controller
@RequestMapping(value = "/manage/product")
public class ProductManageController extends CategoryBaseController {

//    测试用
    private static Logger logger = LoggerFactory.getLogger(ProductManageController.class);

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IProductService iProductService;

    @Autowired
    private IFileService iFileService;

    @RequestMapping(value = "save.do")
    @ResponseBody
    public ServerResponse productSave(HttpSession httpSession, Product product) {
//        判断是否为管理员
        ServerResponse isAdmin = checkAdmin(httpSession);
        if (isAdmin.isSuccess()) {
            return iProductService.saveOrUpdateProduct(product);
        } else {
            return ServerResponse.createByErrorMessage("无权操作");
        }
    }

    /**
     * 保存产品状态
     *
     * @param httpSession
     * @param productId
     * @param status
     * @return
     */
    @RequestMapping(value = "set_sale_status.do")
    @ResponseBody
    public ServerResponse setSaleStatus(HttpSession httpSession, Integer productId, Integer status) {
        ServerResponse isAdmin = checkAdmin(httpSession);
        if (isAdmin.isSuccess()) {
            return iProductService.setSaleStatus(productId, productId);
        } else {
            return ServerResponse.createByErrorMessage("无权操作");
        }
    }

    /**
     * 获取产品详情
     *
     * @param httpSession
     * @param productId
     * @return
     */
    @RequestMapping(value = "get_detail.do")
    @ResponseBody
    public ServerResponse getDetail(HttpSession httpSession, Integer productId) {

        ServerResponse isAdmin = checkAdmin(httpSession);
        if (isAdmin.isSuccess()) {
//            业务逻辑代码
            return iProductService.manageProductDetail(productId);
        } else {
            return ServerResponse.createByErrorMessage("无权操作");
        }
    }

    /**
     * 产品分页
     *
     * @param httpSession
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "list.do")
    @ResponseBody
    public ServerResponse getList(HttpSession httpSession, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "10") int pageSize) {
        ServerResponse isAdmin = checkAdmin(httpSession);
        if (isAdmin.isSuccess()) {
//            业务逻辑代码
            return iProductService.getProductList(pageNum, pageSize);
        } else {
            return ServerResponse.createByErrorMessage("无权操作");
        }
    }

    /**
     * 产品查询
     *
     * @param httpSession
     * @param productName 根据产品名字查询
     * @param productId   根据产品id查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "search.do")
    @ResponseBody
    public ServerResponse productSearch(HttpSession httpSession, String productName, Integer productId, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "10") int pageSize) {
        ServerResponse isAdmin = checkAdmin(httpSession);
        if (isAdmin.isSuccess()) {
//            业务逻辑代码
            return iProductService.searchProduct(productName, productId, pageNum, pageSize);
        } else {
            return ServerResponse.createByErrorMessage("无权操作");
        }
    }

    /**
     * 上传产品图
     *
     * @param multipartFile
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "upload.do")
    @ResponseBody
    public ServerResponse upload(HttpSession httpSession, @RequestParam(value = "upload_file", required = false) MultipartFile multipartFile, HttpServletRequest httpServletRequest) {

        ServerResponse isAdmin = checkAdmin(httpSession);
        if (isAdmin.isSuccess()) {
//            管理员相关业务逻辑
//            获取上传路径，服务器中的路径。这里获取不到上传路径，会在service层报空指针错误
            String path = httpServletRequest.getSession().getServletContext().getRealPath("upload");
            logger.info("上传路径为：{}", path);
            String targetFileName = iFileService.upload(multipartFile, path);

//           拼接出已上传的文件路径
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;

//           组装url以返回给前端
            Map fileMap = Maps.newHashMap();
            fileMap.put("uri", targetFileName);
            fileMap.put("url", url);
            return ServerResponse.createBySuccess(fileMap);

        } else {
            return ServerResponse.createByErrorMessage("无管理员操作权限");
        }
    }

    /**
     * 富文本上传
     *
     * @param httpSession
     * @param multipartFile
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "richtext_img_upload.do")
    @ResponseBody
    public Map richtextImgUpload(HttpSession httpSession, @RequestParam(value = "upload_file", required = false) MultipartFile multipartFile, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map resultMap = Maps.newHashMap();
//        判断管理员权限
        User user = (User) httpSession.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            resultMap.put("success", false);
            resultMap.put("msg", "请登录管理员");
            return resultMap;
        }

        if (iUserService.checkAdminRole(user).isSuccess()) {
//            获取上传路径
            String path = httpServletRequest.getSession().getServletContext().getRealPath("upload");
//            获取上传后的目标文件
            String targetFileName = iFileService.upload(multipartFile, path);
            if (StringUtils.isBlank(targetFileName)) {
                resultMap.put("success", false);
                resultMap.put("msg", "上传失败");
                return resultMap;
            }
//            上传成功，获取文件url
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
            resultMap.put("success", true);
            resultMap.put("msg", "上传成功");
            resultMap.put("file_path", url);
            httpServletResponse.addHeader("Access-Control-Allow-Headers", "X-File-Name");
            return resultMap;
        } else {
            resultMap.put("success", false);
            resultMap.put("msg", "无权限操作");
            return resultMap;
        }

    }


}
